<script setup>
import {
  ElMessage, ElForm, ElRow, ElCol, ElFormItem, ElSelect, ElOption,
} from 'element-plus';
import { ref } from 'vue';
import cyber from '../../../lib/cybercloud';

const userWorkFormRefs = ref({});

let show = ref(false);
let loading = ref(false);
const footerPreset = ref('NORMAL');
const props = defineProps({
  dialogConfig: {
    type: Object,
    default() {
      return {};
    },
  },
  enums: {
    type: Object,
    default() {
      return {};
    },
  },
});
const dialogConfig = ref(props.dialogConfig);

function positiveIntegerChange(value, index, key) {
  dialogConfig.value.formData
    .details[index].items[key].value = value;
}

const emit = defineEmits(['submitSuccess', 'closeDialog']);

function closeDialog() {
  emit('closeDialog');
}
function submitSuccess() {
  emit('submitSuccess');
}
// 弹出框取消
function cancel() {
  if (dialogConfig.value.apiInfo.body.params === undefined) {
    dialogConfig.value.apiInfo.body = {};
  } else {
    dialogConfig.value.apiInfo.body.params = {};
  }
  Object.values(dialogConfig.value.formData.details)
    .forEach((detail) => {
      Object.values(detail.items)
        .forEach((item) => {
          if (item.show) {
            item.value = '';
            if (item.type === 'selectRemote') {
              item.selectRemote.optionsData.data = [];
            } else if (item.type === 'inputNumberInt') {
              item.value = 1;
            }
          }
        });
    });
  // 关闭弹出框
  show = false;
  // 触发关闭弹框回传
  closeDialog();
}
// 打开弹出框
function openDialog() {
  show.value = true;
}
// 验证是否，返回错误
function checkValid(valid, msg) {
  if (!valid) throw Error(msg);
}
// 表单提交
const enter = async (apiInfo) => {
  loading = true;
  await userWorkFormRefs.value[dialogConfig.value.formRef].validate((valid) => {
    try {
      checkValid(valid, '请检查数据!');
      const params = {};
      const list = dialogConfig.value.formData.details;
      Object.values(list)
        .forEach((detail) => {
          Object.values(detail.items)
            .forEach((item) => {
              if (item.post) {
                params[item.code] = item.value;
              }
            });
        });
      if (apiInfo.body.params === undefined) {
        apiInfo.body = params;
      } else {
        apiInfo.body.params = params;
      }
      cyber.request({
        method: apiInfo.method,
        url: apiInfo.url,
        data: apiInfo.body,
      })
        .then((response) => {
          if (response.success) {
            ElMessage.success('操作成功');
            cancel();
            submitSuccess();
          } else {
            ElMessage.error(response.message);
          }
          loading = false;
        })
        .catch(() => {
          loading = false;
          ElMessage.error('失败');
        });
    } catch (e) {
      if (e.message !== 'NO') {
        ElMessage.error(e.message);
      }
      loading = false;
    }
  });
};

// 远程搜索数据
function remoteMethod(query, name, urlAdd, methodType, params, index, key, attribute) {
  dialogConfig.value.formData
    .details[index].items[key].options.loading = true;
  if (query && params.filters.length > 0) {
    params.filters[0].value = query;
  }
  cyber.request({
    method: methodType,
    url: urlAdd,
    data: params,
  })
    .then((response) => {
      if (response.success) {
        const list = response.data.objects;
        const optionsList = [];
        Object.values(list)
          .forEach((item) => {
            const option = {
              label: '',
              value: '',
              code: '',
            };
            Object.keys(item)
              .forEach((attr) => {
                if (attribute.label === attr) {
                  option.label = item[attr];
                }
                if (attribute.value === attr) {
                  option.value = item[attr];
                }
                if (attribute.code === attr) {
                  option.code = item[attr];
                }
              });
            if (option.label && option.value) {
              optionsList.push(option);
            }
          });
        dialogConfig.value.formData
          .details[index].items[key].selectRemote.optionsData.data = optionsList;
        dialogConfig.value.formData
          .details[index].items[key].options.loading = false;
      } else {
        ElMessage.error('获取数据失败');
        dialogConfig.value.formData
          .details[index].items[key].options.loading = false;
      }
    }).catch(() => {
      ElMessage.error('获取数据失败');
      dialogConfig.value.formData
        .details[index].items[key].options.loading = false;
    });
}

defineExpose({
  openDialog,
});
</script>
<template>
  <div>
    <C-Dialog v-model:visible="show"
              :title="dialogConfig.title"
              :loading="loading"
              :footerPreset="footerPreset"
              :options="dialogConfig.options"
              @cancel="cancel"
              @enter="enter(dialogConfig.apiInfo)">
      <el-form :ref="el => { if (el) userWorkFormRefs[dialogConfig.formRef] = el }"
               :model="dialogConfig.formData"
               :rules="dialogConfig.rules"
               :label-width="120"
               label-position="right"
      >
        <div v-if="dialogConfig.formData!==undefined">
          <div v-for="(group,index) of dialogConfig.formData.details" :key="index">
            <el-row>
              <el-col class="dialogSpan" :span="24">{{ group.name }}</el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="item.span? 24/item.span : 24 "
                      v-for="(item,key) of group.items" :key="key">
                <el-form-item v-if="item.show" :label="item.name"
                              :prop="`details[${index}].items[${key}].value`"
                              :rules="item.rules.rulesName"
                >
                  <el-input v-if="item.type === 'input'"
                            :style="item.options.style"
                            :disabled="item.options.readonly"
                            :placeholder="item.options.placeholder"
                            :ref="'formInput_'+index+'_'+key"
                            v-model="item.value"/>
                  <el-select v-else-if="item.type === 'selectRemote'"
                             :style="item.options.style"
                             :disabled="item.options.readonly"
                             :ref="'formSelectRemote_'+index+'_'+key"
                             filterable
                             remote
                             :loading="item.options.loading"
                             :clearable="true"
                             reserve-keyword
                             :placeholder="item.options.placeholder"
                             :remote-method="(query) =>
                               remoteMethod(query,
                                    'formSelectRemote_'+index+'_'+key,
                                    item.selectRemote.url,
                                    item.selectRemote.method,
                                    item.selectRemote.params,
                                    index,
                                    key,
                                    item.selectRemote.optionsData.attribute
                                    )"
                             v-model="item.value">
                    <el-option
                      v-for="optionTemp in item.selectRemote.optionsData.data"
                      :key="optionTemp.value"
                      :label="optionTemp.label"
                      :value="optionTemp.value">
                      <span style="float: left">{{ optionTemp.code }}</span>
                      <span style=" float: right;
                        color: var(--el-text-color-secondary);
                        font-size: 13px;"
                      >{{ optionTemp.label }}</span
                      >
                    </el-option>
                  </el-select>
                  <el-select v-else-if="item.type === 'select'"
                             :style="item.options.style"
                             :disabled="item.options.readonly"
                             :ref="'formSelect_'+index+'_'+key"
                             :placeholder="item.options.placeholder"
                             :clearable="
                             item.options.clearable === undefined ? true:item.options.clearable "
                             v-model="item.value"
                  >
                    <el-option
                      v-for="optionTemp in
                       enums[item.enumsName] !== undefined ?enums[item.enumsName]:[] "
                      :key="optionTemp.value"
                      :label="optionTemp.label"
                      :value="optionTemp.value">
                    </el-option>
                  </el-select>
                  <el-input-number v-else-if="item.type === 'inputNumberPositive'"
                                   style="width:auto"
                                   :disabled="item.options.readonly"
                                   :precision="item.options.precision"
                                   @change="(value) =>positiveIntegerChange(value,index,key)"
                                   :ref="'inputNumberInt_'+index+'_'+key"
                                   v-model="item.value"
                                   :min="item.options.min" :max="item.options.max"
                                   :step="item.options.step" step-strictly
                  ></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-form>
    </C-Dialog>
  </div>

</template>
<style scoped lang="sass">
@import "InsertDialog.sass"
</style>
